﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;
using DevExpress.Utils;
using DevExpress.Utils;
using DevExpress.XtraGrid;

namespace ReportGenerators.QuanLyKho.ThongKeChiTietNhapXuatKho
{
    public partial class FrmThongKeChiTietNhapXuatKho : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeChiTietNhapXuatKho()
        {
            InitializeComponent();
        }

        private void FrmThongKeNhapXuatTon_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dsThongKeChiTietNhapXuatKho.Detail' table. You can move, or remove it, as needed.
            //this.vatTuHangHoaTableAdapter.Fill(this.dsThongKeChiTietNhapXuatKho.VatTuHangHoa);
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKho.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucKho.Instance.DataTable, "Ten", 0).DefaultView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                cmbNhọmHang.DataSource = DanhMucNhomVatTuHangHoa.Instance.DataView;
                cmbNhọmHang.DisplayColumn = "Ten";
                cmbNhọmHang.ValueColumn = "ID";
                cmbNhọmHang.AddVisibleColumn("Ma", "Mã");
                cmbNhọmHang.AddVisibleColumn("Ten", "Tên");

                gridControl.DataSource = dsThongKeChiTietNhapXuatKho.Detail;
                gridControlDsVatTuHangHoa.DataSource = dsThongKeChiTietNhapXuatKho.VatTuHangHoa;

                dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
            }
            catch (Exception ex)
            {
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                if (column.FieldName == "TenKho" || column.FieldName == "MaHangHoa" || column.FieldName == "TenHangHoa" ||
                    column.FieldName == "Ngay" || column.FieldName == "DienGiai")
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                else
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }

            try
            {
                StyleFormatCondition styleCondition = new DevExpress.XtraGrid.StyleFormatCondition();
                styleCondition.Appearance.BackColor = Color.SkyBlue;
                styleCondition.Appearance.Options.UseBackColor = true;
                styleCondition.Condition = FormatConditionEnum.Equal;
                styleCondition.Column = gridView.Columns["DienGiai"];
                styleCondition.Value1 = string.Format("Tồn đầu kỳ: {0}", dtNgayBatDau.Text);
                styleCondition.ApplyToRow = true;
                gridView.FormatConditions.Add(styleCondition);

                chkChooseAllVatTuHangHoa.Checked = false;
                rdoTKNhapXuatKhongCoHoaDon.Checked = false;
                rdoTKToanBo.Checked = true;
                chkTKPhieuNhap.Checked = true;
                chkTKPhieuXuat.Checked = true;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            FormatNumberInGridView(gridViewDsVatTuHangHoa);
            FormatNumberInGridView(gridView);
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }
        private void rdoTKToanBo_CheckedChanged(object sender, EventArgs e)
        {
            rdoTKNhapXuatKhongCoHoaDon.Checked = !rdoTKToanBo.Checked;
        }
        private void rdoTKNhapXuatKhongCoHoaDon_CheckedChanged(object sender, EventArgs e)
        {
            rdoTKToanBo.Checked = !rdoTKNhapXuatKhongCoHoaDon.Checked;
        }
        private void cmbKhoNhap_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void CalculateSoLuongTonTruocTonSauTungPhieu(SqlCommand cmd, DateTime ngayBatDau, bool showTonDauKy)
        {
            Guid beforekhoID = Guid.Empty; Guid curKhoID = Guid.Empty;
            Guid beforeVatTuHangHoaID = Guid.Empty; Guid curVatTuHangHoaID = Guid.Empty;
            DataRow beforeRow = null; DataRow curRow = null;
            int i = 0;

            while (dsThongKeChiTietNhapXuatKho.Detail.Count > i)
            {
                FrmProgressBarDev.Status = "Đã xử lý " + i + " lịch sử nhập xuất kho";

                if (i > 0) beforeRow = dsThongKeChiTietNhapXuatKho.Detail.Rows[i - 1];
                curRow = dsThongKeChiTietNhapXuatKho.Detail.Rows[i];

                if (beforeRow != null && beforeRow["KhoID"] is Guid && (Guid)beforeRow["KhoID"] != Guid.Empty) beforekhoID = (Guid)beforeRow["KhoID"];
                if (beforeRow != null && beforeRow["VatTuHangHoaID"] is Guid && (Guid)beforeRow["VatTuHangHoaID"] != Guid.Empty)
                    beforeVatTuHangHoaID = (Guid)beforeRow["VatTuHangHoaID"];
                if (curRow != null && curRow["KhoID"] is Guid && (Guid)curRow["KhoID"] != Guid.Empty) curKhoID = (Guid)curRow["KhoID"];
                if (curRow != null && curRow["VatTuHangHoaID"] is Guid && (Guid)curRow["VatTuHangHoaID"] != Guid.Empty)
                    curVatTuHangHoaID = (Guid)curRow["VatTuHangHoaID"];

                if (beforekhoID == Guid.Empty || beforeVatTuHangHoaID == Guid.Empty ||
                    curKhoID != beforekhoID || curVatTuHangHoaID != beforeVatTuHangHoaID)
                {
                    TonKho tonKho = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, ngayBatDau, curKhoID, curVatTuHangHoaID);
                    curRow["TonTruoc"] = tonKho.SoLuong;
                    if (curRow["SoLuongNhap"] is decimal && (decimal)curRow["SoLuongNhap"] > 0)
                    {
                        curRow["TonSau"] = tonKho.SoLuong + (decimal)curRow["SoLuongNhap"];
                    }
                    else if (curRow["SoLuongNhap"] is decimal && (decimal)curRow["SoLuongXuat"] > 0)
                    {
                        curRow["TonSau"] = tonKho.SoLuong - (decimal)curRow["SoLuongXuat"];
                    }
                    else if (curRow["TonTruoc"] is decimal)
                    {
                        curRow["TonSau"] = curRow["TonTruoc"];
                    }
                    if (showTonDauKy)
                    {
                        //Thêm row tồn đầu kỳ 
                        DataRow rowTonDauKy = dsThongKeChiTietNhapXuatKho.Detail.NewRow();
                        rowTonDauKy["DienGiai"] = string.Format("Tồn đầu kỳ: {0}", dtNgayBatDau.Text);
                        rowTonDauKy["TonTruoc"] = tonKho.SoLuong;
                        dsThongKeChiTietNhapXuatKho.Detail.Rows.InsertAt(rowTonDauKy, i);
                        i++;
                    }
                }
                else
                {

                    if (beforeRow["TonSau"] is decimal) curRow["TonTruoc"] = beforeRow["TonSau"];

                    if (curRow["TonTruoc"] is decimal && (decimal)curRow["SoLuongNhap"] > 0)
                    {
                        curRow["TonSau"] = (decimal)curRow["TonTruoc"] + (decimal)curRow["SoLuongNhap"];
                    }
                    else if (curRow["TonTruoc"] is decimal && (decimal)curRow["SoLuongXuat"] > 0)
                    {
                        curRow["TonSau"] = (decimal)curRow["TonTruoc"] - (decimal)curRow["SoLuongXuat"];
                    }
                    else if (curRow["TonTruoc"] is decimal)
                    {
                        curRow["TonSau"] = curRow["TonTruoc"];
                    }
                }
                i++;
            }
        }
        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);

            if (chkTKPhieuNhap.Checked == false && chkTKPhieuXuat.Checked == false)
            {
                //K hiện gì.
                return;
            }
            BasicForms.FrmProgressBarDev.StartShowProgress();
            try
            {
                string vatTuHangHoaCondition = "1 = 1";
                if (!chkChooseAllVatTuHangHoa.Checked)
                {
                    vatTuHangHoaCondition = "A.VatTuHangHoaID IN  (";
                    foreach (DataRow row in dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }
                else if ((cmbNhọmHang.EditValue is Guid) && (Guid)cmbNhọmHang.EditValue != Guid.Empty)
                {
                    vatTuHangHoaCondition = "A.VatTuHangHoaID IN  (";
                    foreach (DataRow row in dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }

                string khoCondition = "1 = 1";
                if (cmbKho.EditValue != null && (Guid)cmbKho.EditValue != Guid.Empty)
                    khoCondition += string.Format("AND A.KhoID = '{0}'", cmbKho.EditValue);

                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;
                cmd.CommandText = string.Format("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
                cmd.ExecuteNonQuery();

                colSoChungTuGoc.Visible = true;
                //Tính toán bộ nhập xuất sau đó lọc có hay không có hóa đơn sau.
                #region Template query 
                string queryForNhapKho = string.Format("SELECT A.KhoID, A.VatTuHangHoaID, CTG.So SoChungTuGoc, B.So, A.Ngay, \n" +
                                                "    D.Ma MaHangHoa, D.Ten TenHangHoa,Kho.Ten TenKho, E.Ten TenNhomHangHoa, D.DonViTinh, \n" +
                                                "    A.SoLuong SoLuongNhap,CAST(0 AS decimal) SoLuongXuat, \n" +
                                                "    A.DonGiaQD DonGia, A.ThanhTienQD ThanhTien, A.GiaThanhToan, A.DienGiai  \n" +
                                                "FROM NhatKyNhapKho A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuID \n" +
                                                "    INNER JOIN VatTuHangHoa D ON A.VatTuHangHoaID = D.ID    \n" +
                                                "    INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                                "    INNER JOIN Kho ON A.KhoID = Kho.ID    \n" +
                                                "    LEFT JOIN ChungTu CTG ON B.ChungTuGocID = CTG.ChungTuID \n" +
                                                "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                                "AND  {0}  \n" +
                                                "AND  {1}  \n" ,
                                                vatTuHangHoaCondition, khoCondition);
                string queryForXuatKho = string.Format("SELECT A.KhoID, A.VatTuHangHoaID, CTG.So SoChungTuGoc, B.So, A.Ngay, \n" +
                                                "    D.Ma MaHangHoa, D.Ten TenHangHoa,Kho.Ten TenKho, E.Ten TenNhomHangHoa, D.DonViTinh, \n" +
                                                "    CAST(0 AS decimal) SoLuongNhap, A.SoLuong SoLuongXuat,\n" +
                                                "    A.DonGiaQD DonGia, A.ThanhTienQD ThanhTien, A.GiaThanhToan, A.DienGiai  \n" +
                                                "FROM NhatKyXuatKho A INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuID \n" +
                                                "    INNER JOIN VatTuHangHoa D ON A.VatTuHangHoaID = D.ID    \n" +
                                                "    INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                                "    INNER JOIN Kho ON A.KhoID = Kho.ID    \n" +
                                                "    LEFT JOIN ChungTu CTG ON B.ChungTuGocID = CTG.ChungTuID \n" +
                                                "WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                                "AND  {0}  \n" +
                                                "AND  {1}  \n" ,
                                                vatTuHangHoaCondition, khoCondition);
                string orderBy = "ORDER BY A.KhoID,D.Ma,A.Ngay ";
                #endregion

                //Query toàn bộ để tính toán tồn trước tồn sau.
                cmd.CommandText = string.Format("{0} \n" +
                                                "UNION \n" +
                                                "{1} \n" +
                                                "{2} ",
                                                queryForNhapKho, queryForXuatKho, orderBy);
      
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau.AddSeconds(1));
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeChiTietNhapXuatKho.Detail.Clear();
                da.Fill(dsThongKeChiTietNhapXuatKho.Detail);
                
                CalculateSoLuongTonTruocTonSauTungPhieu(cmd, ngayBatDau, true);
                
                //Kiểm tra tiêu chí lọc chỉ phiếu nhập hay chỉ phiếu xuất k
                if (chkTKPhieuNhap.Checked == true && chkTKPhieuXuat.Checked == false)
                {
                    gridView.ActiveFilterString = "[SoLuongXuat] = 0.0000m";
                }
                else if (chkTKPhieuNhap.Checked == false && chkTKPhieuXuat.Checked == true)
                {
                    gridView.ActiveFilterString = "[SoLuongNhap] = 0.0000m";
                }
                

                if (rdoTKNhapXuatKhongCoHoaDon.Checked)
                {
                    //Chỉ hiện phiếu nhập xuất không kèm hóa đơn
                    colSoChungTuGoc.Visible = false;
                    dsThongKeChiTietNhapXuatKho.Detail.DefaultView.RowFilter = "SoChungTuGoc is NULL";
                }
                else if (rdoTKKhongKemTraLai.Checked)
                {
                    //Thống kê những hóa đơn mua bán trả lại
                    cmd.CommandText = string.Format("SELECT A.So SoChungTuGocLienQuanTraLai FROM ChungTu A INNER JOIN LoaiChungTu LCT ON A.LoaiChungTuID = LCT.ID \n" +
                                                            "WHERE LCT.Ma IN ('HangMuaTraLai', 'HangBanTraLai') \n" +
                                                            "AND @ThoiDiemDau2 <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi2 \n"
                                                            );
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@ThoiDiemDau2", ngayBatDau.AddSeconds(1));
                    cmd.Parameters.AddWithValue("@ThoiDiemCuoi2", ngayKetThuc);

                    da.SelectCommand = cmd;
                    DataTable dtTemp = new DataTable();
                    da.Fill(dtTemp);

                    //Nếu có hóa đơn liên quan đến trả lại thì lọc. K thì thôi
                    if (dtTemp.Rows.Count > 0)
                    {
                        //Đưa các chứng từ này thành SQL Query
                        string chungTuTraLaiCondition = "SoChungTuGoc NOT IN  (";
                        foreach (DataRow row in dtTemp.Rows)
                        {
                            chungTuTraLaiCondition += string.Format("'{0}', ", row["SoChungTuGocLienQuanTraLai"]);
                        }
                        if (chungTuTraLaiCondition.EndsWith("', ")) chungTuTraLaiCondition = chungTuTraLaiCondition.Substring(0, chungTuTraLaiCondition.Length - 2) + ")";
                        else chungTuTraLaiCondition = "";
                        //Bỏ những hóa đơn này ra khỏi báo cáo.
                        dsThongKeChiTietNhapXuatKho.Detail.DefaultView.RowFilter = chungTuTraLaiCondition;
                    }
                }
                else if(rdoTKToanBo.Checked)
                {
                    //Chọn tất thì k filter gì
                    dsThongKeChiTietNhapXuatKho.Detail.DefaultView.RowFilter = "";
                }
                gridControl.DataSource = dsThongKeChiTietNhapXuatKho.Detail.DefaultView;
                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                if(con.State == ConnectionState.Open) con.Close();
                con = null;
            }
            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string more1 = "";
            if ((cmbKho is Guid) && (Guid)cmbKho.EditValue != Guid.Empty) 
                more1 = string.Format(" Kho nhập: {0}", DanhMucKho.Instance.GetByID((Guid)cmbKho.EditValue).Ten);
            PrintWithHeader(true, gridControl, true, true, "Thống kê chuyển kho", more1);
        }

        private void cmbNhọmHang_EditValueChanged(object sender, EventArgs e)
        {
            if (!(cmbNhọmHang.EditValue is Guid) || (Guid)cmbNhọmHang.EditValue == Guid.Empty)
            {
                return; 
            }

            try
            {
                if (cmbNhọmHang.EditValue is Guid && (Guid)cmbNhọmHang.EditValue != Guid.Empty)
                {
                    //Dieu kien loc la ID = cmbNhomVatTuHangHoa.EditValue + ID cac nhom con.
                    string filterNhomCon = "CONVERT('{" + cmbNhọmHang.EditValue.ToString() + "}','System.Guid'), ";
                    DanhMucNhomVatTuHangHoa cacNhomCon = DanhMucNhomVatTuHangHoa.Instance.GetNhomVatTuHangHoaCon((Guid)cmbNhọmHang.EditValue);
                    foreach (NhomVatTuHangHoa nhomCon in cacNhomCon)
                    {
                        filterNhomCon += "CONVERT('{" + nhomCon.ID + "}','System.Guid'), ";
                        //filterNhomCon += string.Format(", '{0}'", nhomCon.ID);
                    }
                    if (filterNhomCon.EndsWith(", ")) filterNhomCon = filterNhomCon.Remove(filterNhomCon.Length - 2);

                    dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Clear();
                    string filter = string.Format("NhomVatTuHangHoaID IN ({0}) AND TrangThai = 1 ", filterNhomCon);
                    dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Filter(filter).DataView.ToTable());
                }
                else
                {
                    dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Clear();
                    dsThongKeChiTietNhapXuatKho.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
                }
                chkChooseAllVatTuHangHoa.Checked = false;
                chkChooseAllVatTuHangHoa.Checked = true;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
    }
}
